<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Class Authorize
 * 用户信息获取流程
 * 1、引导用户进入授权页面同意授权，获取code
 * 2、通过code换取网页授权access_token（与基础支持中的access_token不同）
 * 3、如果需要，开发者可以刷新网页授权access_token，避免过期
 * 4、通过网页授权access_token和openid获取用户基本信息（支持UnionID机制）
 */

class Authorize extends CI_Controller {
    private $code;
    private $openid;
    private $access_token;
    private $refresh_token;
    private $userInfo;

    public function index($mode = 'base'){
        $this->load->helper('url');
        $params = array("appId"=>config_item("appId"),"appSecret"=>config_item("appSecret"));
        $this->load->library('Wechatsdk', $params);
        if(isset($_GET["code"])) {
            //已经授权，获取openid或用户信息
            $this->code = $_GET["code"];
            $this->getOpenId();
            //var_dump($this->openid);
            if($mode == 'info'){
                $this->getUserInfo();
                //echo $this->userInfo->nickname;
                //var_dump($this->userInfo);
            }
        }else{
            //没有授权，获取授权
            $this->getScope($mode);
        }
        //todo 加载业务处理
    }

    /**
     * 获取scope授权code
     * @param string $mode
     * base: snsapi_base授权，无确认提示，仅能获取openid
     * base：snsapi_userinfo授权，需要用户点击确认进行授权，可获取用户其它基本信息
     *
     * 授权完成后，会跳转至redirect_uri/?code=CODE&state=STATE
     */
    private function getScope($mode = 'base'){

        if($mode == 'base'){
            $redirect_uri = urlencode("http://lipengfan.cc/index.php/oauth/base");
            $scopeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".config_item("appId")."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
            redirect($scopeUrl);
        }
        if($mode == 'info'){
            $redirect_uri = urlencode("http://lipengfan.cc/index.php/oauth/info");
            $scopeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".config_item("appId")."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
            redirect($scopeUrl);
        }
    }

    /**
     * 通过授权code，获取openid
     */
    private function getOpenId(){
        $openIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".config_item("appId")."&secret=".config_item("appSecret")."&code=".$this->code."&grant_type=authorization_code";
        $openIdInfo = json_decode($this->wechatsdk->httpGet($openIdUrl));
        $this->openid = $openIdInfo->openid;
        $this->access_token = $openIdInfo->access_token;
        $this->refresh_token = $openIdInfo->refresh_token;
    }

    /**
     * 获取用户信息
     */
    private function getUserInfo(){
        $userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=".$this->access_token."&openid=".$this->openid."&lang=zh_CN";
        $this->userInfo = json_decode($this->wechatsdk->httpGet($userInfoUrl));

    }
}
